/*
 * Copyright (C) 2009 Leandro Aparecido <lehphyro@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.metalframework.jsf.scope.impl;

import javax.faces.context.*;
import javax.servlet.http.*;

import org.apache.commons.lang.*;
import org.metalframework.jsf.scope.*;
import org.metalframework.util.*;
import org.slf4j.*;


public class PageScope extends AbstractFacesScope {

	private static final String DEFAULT_COOKIE_NAME = PageScope.class.getName() + ".lastPage";

	private static final Logger logger = LoggerFactory.getLogger(PageScope.class);
	
	private String cookieName;
	
	public PageScope() {
		this(DEFAULT_COOKIE_NAME);
	}

	public PageScope(String cookieName) {
		this.cookieName = cookieName;
	}

	@Override
	public void onStartRequest() {
		Object obj = FacesContext.getCurrentInstance().getExternalContext().getRequest();
		if (!(obj instanceof HttpServletRequest)) {
			throw new UnsupportedOperationException("Only HTTP servlet environment is supported");
		}
		HttpServletRequest request = (HttpServletRequest) obj;
		Cookie[] cookies = request.getCookies();
		if (cookies == null) {
			logger.debug("No last page cookie found, page scope must be cleared");
			clear();
		} else {
			Cookie pageCookie = null;
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(cookieName)) {
					pageCookie = cookie;
					break;
				}
			}
			handleCookie(pageCookie);
		}
		
		obj = FacesContext.getCurrentInstance().getExternalContext().getResponse();
		HttpServletResponse response = (HttpServletResponse) obj;
		response.addCookie(createCookie());
	}
	
	@Override
	protected FacesScopeType getType() {
		return FacesScopeType.PAGE;
	}
	
	protected void handleCookie(Cookie cookie) {
		if (cookie == null) {
			logger.debug("No last page cookie found, page scope must be cleared");
			clear();
		} else {
			String lastPage = cookie.getValue();
			String currentPage = FacesUtils.getCurrentPage();
			logger.debug("Last page viewed is [{}], current page is [{}]", lastPage, currentPage);
			
			if (StringUtils.equals(lastPage, currentPage)) {
				logger.debug("Still in the same page, page scope must be kept");
			} else {
				logger.debug("Current page is not the same as last, page scope must be cleared");
				clear();
			}
		}
	}
	
	protected Cookie createCookie() {
		Cookie cookie = new Cookie(cookieName, FacesUtils.getCurrentPage());
		cookie.setMaxAge(-1);
		cookie.setPath(FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath());
		
		return cookie;
	}
	
}
